package com.sugon.modules.sys.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.cait.service.rescenter.UserInfo;
import com.sugon.cache.J2CacheUtils;
import com.sugon.dao.SysMenuDao;
import com.sugon.dao.SysUserDao;
import com.sugon.entity.SysMenuEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.modules.sys.service.IResCenterAuthenticator;
import com.sugon.modules.sys.service.IUserManager;
import com.sugon.service.SysUserService;
import com.sugon.utils.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class UserManagerImpl implements IUserManager {

    @Resource
    private IResCenterAuthenticator resCenterAuthenticator;
    @Resource
    private SysUserService userService;
    @Resource
    private SysMenuDao sysMenuDao;
    @Resource
    private SysUserDao sysUserDao;

    /**
     * loginSuccessInit
     *
     * @param identityToken
     * @param userId
     */
    @Override
    public void loginSuccessInit(String identityToken, String userId) {
        // 把当前用户放入到session中
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(true);
        SysUserEntity ermsUser = null;
        if (StrUtil.isNotEmpty(identityToken)) {
            UserInfo resCenterUser = resCenterAuthenticator.getUserByToken(identityToken);
            Assert.notNull(resCenterUser, "获取远程认证中心中用户[{}]信息失败！", identityToken);
            ermsUser = userService.queryByUnionId(resCenterUser.getUserId());
            Assert.notNull(ermsUser, "请先登录ERMS完成认证后再进行审核操作！", identityToken);
            session.setAttribute(Constant.IDENTITY_TOKEN, identityToken);
        } else if (StrUtil.isNotEmpty(userId)) {
            ermsUser = userService.queryObject(userId);
            Assert.notNull(ermsUser, "用户[{}]信息不存在，请确认！", userId);
        }
        /*
        理论上不会出现这种场景
        如果出现，那么不允许执行后面的逻辑
         */
        if (ermsUser != null) {
            session.setAttribute(Constant.CURRENT_USER, ermsUser);
            //系统管理员，拥有最高权限
            List<String> permsList;
            if (Constant.SUPER_ADMIN.equals(ermsUser.getUserId())) {
                List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<String, Object>());
                permsList = new ArrayList<>(menuList.size());
                for (SysMenuEntity menu : menuList) {
                    permsList.add(menu.getPerms());
                }
            } else {
                permsList = sysUserDao.queryAllPerms(ermsUser.getUserId());
            }
            J2CacheUtils.put(Constant.PERMS_LIST + ermsUser.getUserId(), permsList);
        }
    }
}
